<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { getSsoSmsCode, ssoMobileLogin, useGetOrgInfo, userAuthInfo, userCurrentPrivileges, userCurrentUserInfo } from '@fl/api/iam-api'
import { SubmitBtn } from '@fl/components'
import { getAccessToken } from '@fl/logics/authentication'
import { ElForm, ElFormItem } from 'element-plus'
import WujieVue from 'wujie-vue3'

const { bus } = WujieVue

const { push } = useRouter()

type IForm = {
    phone: string
    verificationCode: string
}

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<IForm>({
    phone: '',
    verificationCode: '',
})

const rules = reactive<FormRules<IForm>>({
    phone: [
        {
            message: '请输入手机号',
            required: true,
        },
        { message: '手机号码格式不正确', pattern: /^1[3-9]\d{9}$/, trigger: 'blur' },
    ],
    verificationCode: [
        {
            message: '请输入验证码',
            required: true,
        },
    ],
})

const veryfyCodeFirstSending = ref(false)
const countdown = ref(0)
const verifyLabel = computed(() => {
    if (unref(veryfyCodeFirstSending)) {
        if (unref(countdown) > 0)
            return `${unref(countdown)}秒后重发`
        else
            return '重新发送'
    }
    else { return '发送验证码' }
})
const { isPending: isPendingCode, mutateAsync: mutateCodeAsync } = getSsoSmsCode()
const { isPending: isPendingLogin, mutateAsync: mutateLoginAsync } = ssoMobileLogin()
const { isLoading: isLoadingUserInfo, refetch: refetchUserInfo } = userCurrentUserInfo(false)
const { isLoading: isLoadingPrivilege, refetch: refetchPrivilege } = userCurrentPrivileges(false)
const { isLoading: isLoadingOrgInfo, refetch: refetchOrgInfo } = useGetOrgInfo(false)

const isPending = computed(() => isPendingLogin.value || isLoadingUserInfo.value || isLoadingPrivilege.value || isLoadingOrgInfo.value) // 是否正在请求中

async function sendVerifyCode() {
    const isValid = unref(ruleFormRef)!.validateField('phone')
    if (!isValid) {
        return false
    }

    const result = await mutateCodeAsync(ruleForm)
    if (result) {
        // 发送验证码
        veryfyCodeFirstSending.value = true
        countdown.value = 60
        startCountdown()
        return true
    }
}

function startCountdown() {
    const interval = setInterval(() => {
        countdown.value = countdown.value - 1
        if (unref(countdown) === 0)
            clearInterval(interval)
    }, 1000)
}

async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return false

    const isValid = await formEl.validate()
    if (!isValid) {
        return false
    }

    const result = await mutateLoginAsync(ruleForm)
    if (result) {
        await refetchUserInfo()
        await refetchPrivilege()
        await refetchOrgInfo()

        bus.$emit('passAndJump', getAccessToken(), '/index')
        push('/')

        userAuthInfo().then((res) => {
            window.sessionStorage.setItem('USER_ID', res.id)
        })
    }
}
</script>

<template>
    <ElForm ref="ruleFormRef"
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            @submit.prevent
    >
        <div class="mb-16 flex flex-col gap-12">
            <ElFormItem label="手机号"
                        prop="phone"
            >
                <el-input v-model="ruleForm.phone"
                          placeholder="请输入手机号"
                          size="large"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="验证码"
                        prop="verificationCode"
            >
                <div class="flex w-full items-center">
                    <el-input v-model="ruleForm.verificationCode"
                              placeholder="请输入验证码"
                              size="large"
                              minlength="6"
                              maxlength="6"
                              class="flex-1"
                    />

                    <SubmitBtn type="primary"
                               class="ml-8 h-40 w-100"
                               :disabled="countdown > 0"
                               :loading="isPendingCode"
                               @click="sendVerifyCode"
                    >
                        {{ verifyLabel }}
                    </SubmitBtn>
                </div>
            </ElFormItem>
        </div>

        <ElFormItem>
            <SubmitBtn type="primary"
                       native-type="submit"
                       class="mt-30 rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                       size="large"
                       :loading="isPending"
                       @click="submitForm(ruleFormRef)"
            >
                登录
            </SubmitBtn>
        </ElFormItem>
    </ElForm>
</template>
